package org.example.test;

import org.example.pojo.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClassDemo {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//        Student student=new Student();
//        System.out.println(student);
//        student=reflectNewInstance();
//        System.out.println(student);
//        reflectPrivateField();
        reflectPrivateMethod();
    }
    public static Student reflectNewInstance() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //动态获取Student类
        Class classStudent=Class
                .forName("org.example.pojo.Student");
        //获取Student类的类型为(String,int)的构造方法
        Constructor declaredConstructorStudent=classStudent
                .getDeclaredConstructor(String.class, int.class);
        //允许访问私有的构造函数
        declaredConstructorStudent.setAccessible( true);
        Object objectStudent=declaredConstructorStudent
                .newInstance("李四",20);
        Student student=(Student)objectStudent;
        return student;
    }
    // 反射私有属性
    public static void reflectPrivateField() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class classStudent=Class
                .forName("org.example.pojo.Student");
        Field field=classStudent.getDeclaredField("name");
        Object objectStudent=classStudent.newInstance();
        field.setAccessible(true);
        Student student=(Student)objectStudent;
        field.set(student,"王五");
        String name= (String) field.get( student);
        System.out.println("获取属性值:"+name);
    }
    // 反射私有⽅法
    public static void reflectPrivateMethod()
            throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class classStudent=Class
                .forName("org.example.pojo.Student");
        Method method=classStudent.getDeclaredMethod("function",String.class);
        System.out.println("获取方法名:"+method.getName());
        Object objectStudent=classStudent.newInstance();
        method.invoke(objectStudent,"hello world");
    }
}

